package post

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/gosimple/slug"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostLogic {
	return &UpdatePostLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePostLogic) UpdatePost(in *blog.PostInfo) (*blog.BaseResp, error) {
	// logx.Infof("UpdatePost : %+v ", in)

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 && in.Status != nil { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				post, err := l.svcCtx.Post.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				post.PostStatus = uint16(*in.Status)
				post.PostModifiedDate = now
				err = l.svcCtx.Post.Update(l.ctx, tx, post, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &blog.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Title != nil && len(strings.TrimSpace(*in.Title)) == 0 {
		return nil, errorx.NewInvalidArgumentError("cms.postTitleRequired")
	}

	id := *in.Id
	post, err := l.svcCtx.Post.FindOneNoCache(l.ctx, tx, id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var skipMeta bool
	if in.SkipMeta != nil && *in.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}
	var skipCategory bool
	if in.SkipCategory != nil && *in.SkipCategory > 0 {
		skipCategory = true
	}
	var skipTag bool
	if in.SkipTag != nil && *in.SkipTag > 0 {
		skipTag = true
	}
	var skipContent bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		skipContent = true
	}

	if in.Title != nil {
		post.PostTitle = strings.TrimSpace(*in.Title)
	}
	var text string
	if in.Slug != nil && post.PostName != strings.TrimSpace(*in.Slug) { // slug改变了
		post.PostName = strings.TrimSpace(*in.Slug)
		if len(post.PostName) > 0 {
			slug.Lowercase = false
			text = slug.Make(post.PostName)
		}
	}
	if in.Excerpt != nil {
		post.PostExcerpt = strings.TrimSpace(*in.Excerpt)
	}

	var visibility uint32
	if in.Visibility != nil && *in.Visibility > 0 {
		visibility = *in.Visibility
	}

	var publicDate time.Time
	var isFuturePublicDate bool
	if in.PublicDate != nil && len(*in.PublicDate) > 0 {
		if localTime, err := modelx.ParseLocalTime(*in.PublicDate); err == nil {
			publicDate = localTime
			isFuturePublicDate = true
		}
	}

	var status uint16
	var futureStatus int32  // 未来发布后的状态
	var pendingStatus int32 // 审核后的状态
	if in.Status != nil {
		if *in.Status == uint32(globalkey.PostStatusPublish) { // 发布
			if isFuturePublicDate { // 未来发布
				status = uint16(globalkey.PostStatusFuture)        // 暂为future状态
				if visibility == globalkey.PostVisibilityPrivate { // 未来发布后为private，否则为public
					futureStatus = globalkey.PostStatusPrivate
				} else {
					futureStatus = globalkey.PostStatusPublish
				}
			} else { // 立即发布
				if visibility == globalkey.PostVisibilityPrivate {
					status = uint16(globalkey.PostStatusPrivate)
				} else {
					status = uint16(globalkey.PostStatusPublish)
				}
			}
		} else { // 其他状态
			status = uint16(*in.Status)
			if isFuturePublicDate { // 未来发布
				pendingStatus = globalkey.PostStatusFuture         // 审核后为future状态
				if visibility == globalkey.PostVisibilityPrivate { // 审核且未来发布后为private，否则为public
					futureStatus = globalkey.PostStatusPrivate
				} else {
					futureStatus = globalkey.PostStatusPublish
				}
			} else { // 立即发布
				if visibility == globalkey.PostVisibilityPrivate {
					pendingStatus = globalkey.PostStatusPrivate
				} else {
					pendingStatus = globalkey.PostStatusPublish
				}
			}
		}
		post.PostStatus = status
	}

	if in.CommentStatus != nil {
		if *in.CommentStatus > 0 {
			post.CommentStatus = 1
		} else {
			post.CommentStatus = 0
		}
	}
	if in.Sort != nil {
		post.MenuOrder = int(*in.Sort)
	}
	post.PostModifiedDate = time.Now()

	if visibility == globalkey.PostVisibilityPasswordProtected && in.Password != nil {
		post.PostPassword = strings.TrimSpace(*in.Password)
	}
	if isFuturePublicDate {
		post.PostDate = publicDate
	}
	if len(text) > 0 {
		post.GUID = post.PostDate.Format("/2006/01/02/") + text
	}
	var sticky string
	if in.Sticky != nil && *in.Sticky > 0 {
		switch int32(*in.Sticky) {
		case globalkey.BlogStickyTypeCategory:
			sticky = "category"
		case globalkey.BlogStickyTypeTag:
			sticky = "tag"
		default:
			sticky = "frontpage"
		}
	}

	rel := &model.BlogPostRel{}
	if !skipContent {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogPostDetailColumns.PostID] = map[string][]any{
			"equalTo": {id},
		}
		list, _, err := l.svcCtx.Post.GetDetailList(l.ctx, model.M{
			"pageSize": uint64(1),
			"orderBy":  model.BlogPostDetailColumns.DetailID + " DESC",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			rel.Detail = list[0]
			if in.Content != nil {
				rel.Detail.PostContent = *in.Content
			}
			if in.ContentFiltered != nil {
				rel.Detail.PostContentFiltered = *in.ContentFiltered
			}
		}
	}

	var thumbnailIdMetaId uint64
	var thumbnailUrlMetaId uint64
	var photoCountMetaId uint64
	var futureStatusMetaId uint64
	var pendingStatusMetaId uint64
	// var viewCountMetaId uint64
	// var commentCountMetaId uint64
	// var forwardCountMetaId uint64
	var stickyMetaId uint64
	if !skipMeta {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogPostMetumColumns.PostID] = map[string][]any{
			"equalTo": {id},
		}
		list, _, err := l.svcCtx.Post.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var omids []uint64
			omidMap := make(map[uint64]struct{})
			for _, v := range list {
				if len(v.MetaKey) > 0 && v.MetaValue.Valid {
					switch v.MetaKey { // 先排除特殊Key
					case "_thumbnail_id":
						thumbnailIdMetaId = v.MetaID
					case "_thumbnail_url":
						thumbnailUrlMetaId = v.MetaID
					case "_photo_count":
						photoCountMetaId = v.MetaID
					case "_future_status":
						futureStatusMetaId = v.MetaID
					case "_pending_status":
						pendingStatusMetaId = v.MetaID
					case "_view_count":
						// viewCountMetaId = v.MetaID
					case "_comment_count":
						// commentCountMetaId = v.MetaID
					case "_forward_count":
						// forwardCountMetaId = v.MetaID
					case "_sticky":
						stickyMetaId = v.MetaID
					default:
						omids = append(omids, v.MetaID)
						omidMap[v.MetaID] = struct{}{}
					}
				}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			if len(in.Meta) > 0 {
				for _, v := range in.Meta {
					if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
						continue
					}

					if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
						continue
					}

					var metum model.BlogPostMetum
					metum.PostID = id
					metum.MetaKey = strings.TrimSpace(*v.Key)
					metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

					if v.Id != nil && *v.Id > 0 {
						if _, ok := omidMap[*v.Id]; ok { // 有值且是有效值，为修改，否则为新增
							nmidMap[*v.Id] = struct{}{}
							metum.MetaID = *v.Id
						}
					}

					rel.Meta = append(rel.Meta, &metum)
				}
			}

			for _, mid := range omids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值，应该删除
					rel.DelMetaIds = append(rel.DelMetaIds, mid)
				}
			}
		} else if len(in.Meta) > 0 { // 不存在原值，则都是新增
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.BlogPostMetum
				metum.PostID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}
	if len(sticky) > 0 {
		rel.Meta = append(rel.Meta, &model.BlogPostMetum{
			MetaID:    stickyMetaId,
			PostID:    id,
			MetaKey:   "_sticky",
			MetaValue: null.StringFrom(sticky),
		})
	}
	if futureStatus > 0 {
		rel.Meta = append(rel.Meta, &model.BlogPostMetum{
			MetaID:    futureStatusMetaId,
			PostID:    id,
			MetaKey:   "_future_status",
			MetaValue: null.StringFrom(strconv.FormatInt(int64(futureStatus), 10)),
		})
	}
	if pendingStatus > 0 {
		rel.Meta = append(rel.Meta, &model.BlogPostMetum{
			MetaID:    pendingStatusMetaId,
			PostID:    id,
			MetaKey:   "_pending_status",
			MetaValue: null.StringFrom(strconv.FormatInt(int64(pendingStatus), 10)),
		})
	}

	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {id},
		}
		filterMap[model.BlogAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypePost},
		}
		list, _, err := l.svcCtx.Post.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		mediaUidMap := make(map[uint64]*model.BlogAttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.AttachmentRelationshipID] = v
			}
		}

		allMediaMap := make(map[string]string)
		exclusiveMap := make(map[string]string) // 防删除原有图文中的图片
		if len(in.AllMedia) > 0 {
			for _, v := range in.AllMedia {
				if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
					allMediaMap[*v.Id] = *v.Url
					exclusiveMap[*v.Url] = *v.Id
				}
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
					url = *v.Uri
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				metaData := strings.Join(meta, ";")

				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.BlogAttachmentRelationship{
							AttachmentRelationshipID: uid,
							AttachmentID:             mediaId,
							AttachmentThumbnail:      thumbnail,
							AttachmentOrder:          order,
							AttachmentImageURL:       url,
							AttachmentImageAlt:       altText,
							AttachmentImageMeta:      metaData,
						})
					}
					continue
				}

				media := &model.BlogAttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				}

				if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
					if uri, ok := allMediaMap[*v.Id]; ok {
						media.AttachmentSource = uri
					}
				}

				rel.Media = append(rel.Media, media)
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(thumbnailUrl) > 0 {
				rel.Meta = append(rel.Meta, &model.BlogPostMetum{
					MetaID:    thumbnailIdMetaId,
					MetaKey:   "_thumbnail_id",
					MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
				})
				rel.Meta = append(rel.Meta, &model.BlogPostMetum{
					MetaID:    thumbnailUrlMetaId,
					MetaKey:   "_thumbnail_url",
					MetaValue: null.StringFrom(thumbnailUrl),
				})
			}
			rel.Meta = append(rel.Meta, &model.BlogPostMetum{
				MetaID:    photoCountMetaId,
				MetaKey:   "_photo_count",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(len(rel.Media)), 10)),
			})
		}

		for _, v := range mediaUidMap {
			// "https://www.scentrobe.com/proxy2/static/uploads/image/202411/019325cc-f0c4-7545-b201-bc36eabc4d63.jpg?49669"
			if _, ok := exclusiveMap[v.AttachmentSource]; ok { // 如果在图文中，保留一次
				delete(exclusiveMap, v.AttachmentSource)
				continue
			}

			rel.DelMediaIds = append(rel.DelMediaIds, v.AttachmentRelationshipID)
		}
	}

	if !skipCategory || !skipTag {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogTermRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {id},
		}
		filterMap[model.BlogTermRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.PostTypePost},
		}
		list, _, err := l.svcCtx.Term.GetRelationshipList(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Tags（决定现有的是增还是改）
			var tids []any
			oridMap := make(map[uint64]uint64)
			for _, v := range list {
				tids = append(tids, v.TermID)
				oridMap[v.TermID] = v.TermRelationshipID
			}

			termFilterMap := make(map[string]map[string][]any)
			termFilterMap[model.BlogTermColumns.TermID] = map[string][]any{
				"in": tids,
			}
			terms, _, err := l.svcCtx.Term.GetList(l.ctx, model.M{}, -1, termFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			ocidMap := make(map[uint64]struct{})
			otidMap := make(map[uint64]struct{})
			if len(terms) > 0 {
				for _, v := range terms {
					switch int32(v.Taxonomy) {
					case globalkey.TermTaxonomyCategory: // 是分类
						ocidMap[v.TermID] = struct{}{}
					case globalkey.TermTaxonomyTag: // 是标签
						otidMap[v.TermID] = struct{}{}
					}
				}
			}

			ntidMap := make(map[uint64]struct{})
			// 现有的 CategoryIds（决定原有的是删还是留）
			if !skipCategory && len(in.CategoryIds) > 0 {
				for _, tid := range in.CategoryIds {
					ntidMap[tid] = struct{}{}

					if _, ok := ocidMap[tid]; ok { // 已有，不新增
						continue
					}

					rel.CategoryIds = append(rel.CategoryIds, tid)
				}
			}

			// 现有的 TagIds（决定原有的是删还是留）
			if !skipTag && len(in.TagIds) > 0 {
				for _, tid := range in.TagIds {
					ntidMap[tid] = struct{}{}

					if _, ok := otidMap[tid]; ok { // 已有，不新增
						continue
					}

					rel.TagIds = append(rel.TagIds, tid)
				}
			}

			if !skipCategory {
				for cid := range ocidMap {
					if _, ok := ntidMap[cid]; !ok { // 当前不存在的值，应该删除
						if rid, ok := oridMap[cid]; ok {
							rel.DelTermIds = append(rel.DelTermIds, rid)
						}
					}
				}
			}
			if !skipTag {
				for tid := range otidMap {
					if _, ok := ntidMap[tid]; !ok { // 当前不存在的值，应该删除
						if rid, ok := oridMap[tid]; ok {
							rel.DelTermIds = append(rel.DelTermIds, rid)
						}
					}
				}
			}
		} else {
			if len(in.CategoryIds) > 0 { // 不存在原值，则都是新增
				rel.CategoryIds = in.CategoryIds
			}
			if len(in.TagIds) > 0 { // 不存在原值，则都是新增
				rel.TagIds = in.TagIds
			}
		}
	}

	err = l.svcCtx.Post.Update(l.ctx, tx, post, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &blog.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
